<template>
  <Header />
  <div class="login-page">
    <div class="back-link" v-if="step === 1">
      <el-link class="more" @click="navto('/login')" type="primary" icon="DArrowLeft">返回</el-link>
      <span>首页/忘记密码</span>
    </div>
    <div class="back-link" v-if="step === 2">
      <el-link class="more" @click="step = 1" type="primary" icon="DArrowLeft">返回</el-link>
      <span> 首页 / 忘记密码 / 重置密码</span>
    </div>
    <!-- 第一部分 -->
    <div v-if="step === 1" class="form-container gradient-box">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="form" label-width="140px">
        <el-form-item label="单位名称" prop="enterprise">
          <el-input v-model="form.enterprise" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="公司电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入公司电子邮箱" />
        </el-form-item>
        <el-form-item label="供应商主要联系人" prop="name">
          <el-input v-model="form.name" placeholder="请输入主要联系人姓名" />
        </el-form-item>
        <el-form-item label="供应商主要联系人电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入主要联系人电话" />
        </el-form-item>
        <el-form-item prop="code" label="验证码" v-if="captchaEnabled">
          <div class="register-tip">
            <el-input v-model="form.code" auto-complete="off" placeholder="验证码" style="flex: 0.9">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>

            <div class="register-code">
              <img :src="codeUrl" @click="getCode" class="register-code-img" />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%; height: 42px; background: #347ff7" type="primary" @click="onSubmit"> 下一步 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 第二部分 -->

    <div v-else-if="step === 2" class="form-container gradient-box">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-position="top" class="form" label-width="140px">
        <el-form-item label="请输入密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" placeholder="请输入8位及以上密码" />
          <span class="tips">密码至少包含大小写字母、数字、特殊字符的其中2种</span>
        </el-form-item>
        <el-form-item label="请再次输入密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入密码" />
          <span class="tips">密码至少包含大小写字母、数字、特殊字符的其中2种</span>
        </el-form-item>
        <el-form-item prop="code" label="验证码" v-if="captchaEnabledNext">
          <div class="register-tip">
            <el-input v-model="passwordForm.code" auto-complete="off" placeholder="验证码" style="flex: 0.9">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>

            <div class="register-code">
              <img :src="codeUrlNext" @click="getCodeNext" class="register-code-img" />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%; height: 42px; background: #347ff7" type="primary" @click="onPasswordSubmit"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import Header from "../../components/Header.vue";
import { useRouter } from "vue-router";
import { getCodeImg } from "@/api/login";
import { validateAccount, updatePassword } from "@/api/project";
import { ElMessage, ElMessageBox } from "element-plus";

const captchaEnabled = ref(false);
const captchaEnabledNext = ref(false);
const codeUrl = ref("");
const codeUrlNext = ref("");

const router = useRouter();
const step = ref(1); // 当前步骤
const formRef = ref(null);
const passwordFormRef = ref(null);
//验证成功返回的code
const validateCode = ref("");
// 第一步表单数据
const form = ref({
  enterprise: "",
  creditCode: "",
  email: "",
  name: "",
  phone: "",
  code: "",
});

// 第一步表单校验规则
const rules = {
  enterprise: [{ required: true, message: "单位名称不能为空", trigger: "blur" }],
  creditCode: [{ required: true, message: "统一社会信用代码不能为空", trigger: "blur" }],
  email: [
    { required: true, message: "公司电子邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的电子邮箱地址", trigger: ["blur", "change"] },
  ],
  name: [{ required: true, message: "主要联系人不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "主要联系人电话不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: ["blur", "change"] },
  ],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
};

// 第二步表单数据
const passwordForm = ref({
  password: "",
  confirmPassword: "",
  code: "",
  uuid: "",
});

// 第二步表单校验规则
const passwordRules = {
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d|(?=.*[!@#$%^&*])).{8,}$/,
      message: "密码至少包含大小写字母、数字或特殊字符的其中2种，长度不少于8位",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
};
const getCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      form.value.uuid = res.uuid;
    }
  });
};
const getCodeNext = () => {
  getCodeImg().then((res) => {
    captchaEnabledNext.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabledNext.value) {
      codeUrlNext.value = "data:image/gif;base64," + res.img;
      passwordForm.value.uuid = res.uuid;
    }
  });
};
// 第一步提交
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const { code, ...formDataWithoutCode } = form.value;
      validateAccount(formDataWithoutCode, code)
        .then((res) => {
          if (res.code === 200) {
            validateCode.value = res.data;
            step.value = 2; // 跳转到第二步
            getCodeNext();
          } else {
            getCode();
            console.log("账号信息校验失败");
          }
        })
        .catch(() => {
          getCode();
        });
    } else {
      console.log("第一步表单校验失败");
    }
  });
};

// 第二步提交
const onPasswordSubmit = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      console.log("密码重置成功:", passwordForm.value);
      const { code, password, uuid } = passwordForm.value;

      updatePassword({ id: validateCode.value, password }, code, uuid)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success(`密码重置成功`);

            router.go(-1);
          } else {
            getCodeNext();
            console.log("密码重置失败");
          }
        })
        .catch(() => {
          getCodeNext();
        });
    } else {
      console.log("第二步表单校验失败");
    }
  });
};

const navto = (url) => {
  router.push(url);
};
onMounted(() => {
  getCode();
});
</script>

<style lang="scss" scoped>
.tips {
  font-size: 14px;
  color: #909399;
  margin-left: 5px;
}
.login-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 56px);
  background: url("../../assets/f87147698f07020d4fea348f49da0166.png") no-repeat center center;
  background-size: cover;

  .form-container {
    background: #fff;
    padding: 2rem;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    width: 450px;

    .form {
      width: 100%;
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 25px;
}
.back-link {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
  width: 490px;
  span {
    margin-left: 20px;
  }
}
.register-code {
  height: 30px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.register-code-img {
  height: 34px;
  margin-top: -2px;
}
.register-tip {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
